import 'package:flutter/material.dart';
import '../controls/basic/e_table.dart';
import '../controls/basic/e_tree.dart';
import '../controls/basic/e_card.dart';

class ProjectPage extends StatefulWidget {
  const ProjectPage({super.key, this.onEnterProject});

  // Callback for navigating to acquisition analysis page
  final VoidCallback? onEnterProject;

  @override
  State<ProjectPage> createState() => _ProjectPageState();
}

class _ProjectPageState extends State<ProjectPage> {
  // 当前选中的树节点ID
  String? _selectedNodeId;
  // 当前表格显示的数据
  List<Map<String, dynamic>> _currentTableData = [];
  // 表格列定义
  final List<ETableColumn<Map<String, dynamic>>> _columns = [
    ETableColumn<Map<String, dynamic>>(
      prop: 'testName',
      label: '测试名称',
      width: 120,
      sortable: true,
    ),
    ETableColumn<Map<String, dynamic>>(
      prop: 'channelNumber',
      label: '通道号',
      width: 80,
    ),
    ETableColumn<Map<String, dynamic>>(
      prop: 'measurementType',
      label: '测量类型',
      width: 100,
    ),
    ETableColumn<Map<String, dynamic>>(
      prop: 'measurementQuantity',
      label: '测量量',
      width: 84,
      sortable: true,
    ),
    ETableColumn<Map<String, dynamic>>(
      prop: 'engineeringUnit',
      label: '工程单位',
      width: 96,
    ),
    ETableColumn<Map<String, dynamic>>(
      prop: 'samplingFrequency',
      label: '采样频率',
      width: 100,
      sortable: true,
    ),
    ETableColumn<Map<String, dynamic>>(
      prop: 'storageStartTime',
      label: '存储开始时间',
      width: 160,
      sortable: true,
    ),
    ETableColumn<Map<String, dynamic>>(
      prop: 'recordTime',
      label: '记录时间',
      width: 100,
      sortable: true,
    ),
  ];
  
  // 不同节点对应的表格数据
  final Map<String, List<Map<String, dynamic>>> _nodeDataMap = {
    'category': [
      {'testName': '所有工程概览', 'channelNumber': '--', 'measurementType': '--', 'measurementQuantity': '--', 'engineeringUnit': '--', 'samplingFrequency': '--', 'storageStartTime': '--', 'recordTime': '--'}
    ],
    'drilling1': [
      {'testName': '钻井测试1概览', 'channelNumber': '--', 'measurementType': '--', 'measurementQuantity': '--', 'engineeringUnit': '--', 'samplingFrequency': '--', 'storageStartTime': '--', 'recordTime': '--'}
    ],
    'drilling2': [
      {'testName': '钻井测试2概览', 'channelNumber': '--', 'measurementType': '--', 'measurementQuantity': '--', 'engineeringUnit': '--', 'samplingFrequency': '--', 'storageStartTime': '--', 'recordTime': '--'}
    ],
    'project1-1': [
      {
        'testName': '工程文件1-1数据',
        'channelNumber': 'CH101',
        'pointDescription': '井口振动监测点',
        'measurementType': '加速度',
        'measurementQuantity': '0.8',
        'engineeringUnit': 'm/s²',
        'samplingFrequency': '2000',
        'storageStartTime': '2023-06-01 08:30:00',
        'recordTime': '120',
      },
      {
        'testName': '工程文件1-1数据',
        'channelNumber': 'CH102',
        'pointDescription': '钻杆应力监测点',
        'measurementType': '应力',
        'measurementQuantity': '120',
        'engineeringUnit': 'MPa',
        'samplingFrequency': '1000',
        'storageStartTime': '2023-06-01 08:30:00',
        'recordTime': '120',
      },
    ],
    'project1-2': [
      {
        'testName': '工程文件1-2数据',
        'channelNumber': 'CH103',
        'pointDescription': '井底压力监测点',
        'measurementType': '压力',
        'measurementQuantity': '35',
        'engineeringUnit': 'MPa',
        'samplingFrequency': '500',
        'storageStartTime': '2023-06-02 10:15:00',
        'recordTime': '90',
      },
    ],
    'project1-3': [
      {
        'testName': '工程文件1-3数据',
        'channelNumber': 'CH104',
        'pointDescription': '泥浆流量监测点',
        'measurementType': '流量',
        'measurementQuantity': '50',
        'engineeringUnit': 'L/min',
        'samplingFrequency': '200',
        'storageStartTime': '2023-06-03 14:20:00',
        'recordTime': '60',
      },
      {
        'testName': '工程文件1-3数据',
        'channelNumber': 'CH105',
        'pointDescription': '泥浆温度监测点',
        'measurementType': '温度',
        'measurementQuantity': '45',
        'engineeringUnit': '°C',
        'samplingFrequency': '100',
        'storageStartTime': '2023-06-03 14:20:00',
        'recordTime': '60',
      },
    ],
    'project2-1': [
      {
        'testName': '工程文件2-1数据',
        'channelNumber': 'CH201',
        'pointDescription': '钻头振动监测点',
        'measurementType': '加速度',
        'measurementQuantity': '1.2',
        'engineeringUnit': 'm/s²',
        'samplingFrequency': '2000',
        'storageStartTime': '2023-06-05 09:45:00',
        'recordTime': '180',
      },
    ],
    'project2-2': [
      {
        'testName': '工程文件2-2数据',
        'channelNumber': 'CH202',
        'pointDescription': '井壁压力监测点',
        'measurementType': '压力',
        'measurementQuantity': '42',
        'engineeringUnit': 'MPa',
        'samplingFrequency': '500',
        'storageStartTime': '2023-06-06 13:30:00',
        'recordTime': '150',
      },
      {
        'testName': '工程文件2-2数据',
        'channelNumber': 'CH203',
        'pointDescription': '井壁温度监测点',
        'measurementType': '温度',
        'measurementQuantity': '60',
        'engineeringUnit': '°C',
        'samplingFrequency': '100',
        'storageStartTime': '2023-06-06 13:30:00',
        'recordTime': '150',
      },
    ],
  };

  @override
  void initState() {
    super.initState();
    // 设置初始表格数据为工程概览
    _currentTableData = _nodeDataMap['category'] ?? [];
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        // 左侧树控件包裹在ECard中
        SizedBox(
          width: 250,
          height: double.infinity,
          child: ECard(
            title: '工程文件树',
            headerIcon: Icon(Icons.workspace_premium, size: 18),
            shadowType: CardShadowType.always,
            padding: EdgeInsets.zero,
            body: _buildTreeView(),
          ),
        ),
        // 右侧表格包裹在ECard中
        Expanded(
          child: Container(
            padding: const EdgeInsets.all(16),
            height: double.infinity,
            child: ECard(
              title: '数据表格',
              headerIcon: Icon(Icons.table_chart, size: 18),
              shadowType: CardShadowType.always,
              padding: EdgeInsets.zero,
              body: _buildDataTable(),
              leftBottom: Padding(
                padding: const EdgeInsets.all(16),
                child: ElevatedButton(
                  onPressed: () {
                    print('进入工程按钮点击');
                    // Call the callback to navigate to acquisition analysis page
                    widget.onEnterProject?.call();
                  },
                  child: Row(
                    children:
                    [
                      Icon(Icons.arrow_forward, size: 16),
                      SizedBox(width: 4),
                      Text('进入工程'),
                    ],
                  ),
                  style: ElevatedButton.styleFrom(
                    foregroundColor: Colors.white,
                    backgroundColor: Colors.blue,
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(4),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  // 构建树控件 - 使用 ETree
  Widget _buildTreeView() {
    // 准备树数据 - 重构为分类包含工程的层级结构
    final List<ETreeNode<void>> treeData = [
      ETreeNode<void>(
        id: 'category',
        label: '工程',
        icon: Icons.workspace_premium,
        expanded: true,
        children: [
          // 钻井测试1分类
          ETreeNode<void>(
            id: 'drilling1', 
            label: '钻井测试1', 
            icon: Icons.folder,
            expanded: true,
            children: [
              ETreeNode<void>(
                id: 'project1-1', 
                label: '工程文件1-1', 
                isLeaf: true,
                icon: Icons.file_present,
                actionIcons: [
                  GestureDetector(
                    child: Icon(Icons.edit, size: 14),
                    onTap: () => print('编辑工程文件1-1'),
                    behavior: HitTestBehavior.opaque,
                  ),
                  GestureDetector(
                    child: Icon(Icons.delete, size: 14),
                    onTap: () => print('删除工程文件1-1'),
                    behavior: HitTestBehavior.opaque,
                  ),
                ],
              ),
              ETreeNode<void>(
                id: 'project1-2', 
                label: '工程文件1-2', 
                isLeaf: true,
                icon: Icons.file_present,
                actionIcons: [
                  GestureDetector(
                    child: Icon(Icons.edit, size: 14),
                    onTap: () => print('编辑工程文件1-2'),
                    behavior: HitTestBehavior.opaque,
                  ),
                  GestureDetector(
                    child: Icon(Icons.delete, size: 14),
                    onTap: () => print('删除工程文件1-2'),
                    behavior: HitTestBehavior.opaque,
                  ),
                ],
              ),
              ETreeNode<void>(
                id: 'project1-3', 
                label: '工程文件1-3', 
                isLeaf: true,
                icon: Icons.file_present,
                actionIcons: [
                  GestureDetector(
                    child: Icon(Icons.edit, size: 14),
                    onTap: () => print('编辑工程文件1-3'),
                    behavior: HitTestBehavior.opaque,
                  ),
                  GestureDetector(
                    child: Icon(Icons.delete, size: 14),
                    onTap: () => print('删除工程文件1-3'),
                    behavior: HitTestBehavior.opaque,
                  ),
                ],
              ),
            ],
            actionIcons: [
              GestureDetector(
                child: Icon(Icons.add, size: 14),
                onTap: () => print('在钻井测试1下添加工程'),
                behavior: HitTestBehavior.opaque,
              ),
            ],
          ),
          // 钻井测试2分类
          ETreeNode<void>(
            id: 'drilling2', 
            label: '钻井测试2', 
            icon: Icons.folder,
            expanded: true,
            children: [
              ETreeNode<void>(
                id: 'project2-1', 
                label: '工程文件2-1', 
                isLeaf: true,
                icon: Icons.file_present,
                actionIcons: [
                  GestureDetector(
                    child: Icon(Icons.edit, size: 14),
                    onTap: () => print('编辑工程文件2-1'),
                    behavior: HitTestBehavior.opaque,
                  ),
                  GestureDetector(
                    child: Icon(Icons.delete, size: 14),
                    onTap: () => print('删除工程文件2-1'),
                    behavior: HitTestBehavior.opaque,
                  ),
                ],
              ),
              ETreeNode<void>(
                id: 'project2-2', 
                label: '工程文件2-2', 
                isLeaf: true,
                icon: Icons.file_present,
                actionIcons: [
                  GestureDetector(
                    child: Icon(Icons.edit, size: 14),
                    onTap: () => print('编辑工程文件2-2'),
                    behavior: HitTestBehavior.opaque,
                  ),
                  GestureDetector(
                    child: Icon(Icons.delete, size: 14),
                    onTap: () => print('删除工程文件2-2'),
                    behavior: HitTestBehavior.opaque,
                  ),
                ],
              ),
            ],
            actionIcons: [
              GestureDetector(
                child: Icon(Icons.add, size: 14),
                onTap: () => print('在钻井测试2下添加工程'),
                behavior: HitTestBehavior.opaque,
              ),
            ],
          ),
        ],
        actionIcons: [
          GestureDetector(
            child: Icon(Icons.add, size: 14),
            onTap: () => print('添加分类'),
            behavior: HitTestBehavior.opaque,
          ),
        ],
      ),
    ];

    // 使用ETree组件渲染树结构
    return ETree<void>(
      data: treeData,
      size: ETreeSize.small, // 设置为小尺寸
      selectType: ETreeSelectType.single,
      selectable: true,
      expandOnClickNode: true,
      defaultExpandedKeys: ['category', 'drilling1', 'drilling2'],
      onNodeClick: (node, level) {
        // 节点点击事件处理
        print('节点点击: ${node.label}, 层级: $level');
        // 更新选中的节点并刷新表格数据
        setState(() {
          _selectedNodeId = node.id;
          _currentTableData = _nodeDataMap[node.id] ?? [];
        });
      },
      onCheckChange: (keys) {
        // 节点选中状态变更处理
        print('选中节点: $keys');
      },
      onExpandChange: (nodeId, expanded) {
        // 节点展开/折叠状态变更处理
        print('节点 $nodeId 展开状态: $expanded');
      },
    );
  }

  // 构建表格 - 使用 ETable (Element Plus风格)
  Widget _buildDataTable() {
    return ETable<Map<String, dynamic>>(
      data: _currentTableData,
      columns: _columns,
      border: true,
      striped: true,
      hoverable: true,
      showHeader: true,
      rowKey: 'channelNumber',
      size: 'small',
      highlightCurrentRow: true,
      onRowClick: (row, index) {
        // 行点击事件处理
        print('点击行: $index, 通道号: ${row['channelNumber']}');
      },
      onRowDoubleClick: (row, index) {
        // 行双击事件处理
        print('双击行: $index, 通道号: ${row['channelNumber']}');
      },
    );
  }
}
